package com.qianfeng.excel;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.qianfeng.excel.listeners.ExcelListener;
import com.qianfeng.excel.listeners.OnDoneListener;
import com.qianfeng.excel.utils.Utils;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.io.*;
import java.util.Properties;

/**
 * Created by Jackiechan on 2022/4/24 0:33
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
public class MainApplication extends Application implements OnDoneListener {
    static String path = MainApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    static Properties properties = new Properties();

    private Label wenjian, img, imgDefault, daochu, sheetindexL, wxnlLabel, wxnlJQDLabel;
    private TextField dataFile, imgDir, targetDir, sheetIndex, wxnlTextField;
    private Button selectDataFile, selecttargetDir, selectImgDir, createFile, clear;
    private RadioButton wxnln, wxnly, wxnlr;

    public static void main(String[] args) {

        try {
            path = path.substring(0, path.lastIndexOf("/") + 1);
            properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(path + "config.properties"))));
        } catch (Exception e) {
            e.printStackTrace();
        }
        launch(args);

    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        //选择文件的文字区域
        wenjian = new Label("数据Excel文件：");
        wenjian.setFont(new Font(20));//字体大小
        //填充数据文件的输入框
        dataFile = new TextField();

        //选择图片位置的区域
        img = new Label("住户照片目录");
        img.setFont(new Font(20));

        //用户照片目录
        imgDir = new TextField();
        imgDefault = new Label("默认为Excel文件下img文件夹");
        imgDefault.setFont(new Font(20));


        //选择导出位置的区域
        daochu = new Label("Excel导出位置");
        daochu.setFont(new Font(20));

        //目标文件目录
        targetDir = new TextField();


        GridPane sheetGroup = new GridPane();

        sheetindexL = new Label("住户数据Sheet位置");
        sheetindexL.setFont(new Font(20));
        sheetindexL.setPadding(new Insets(0, 10, 0, 0));
        //sheet位置
        sheetIndex = new TextField();
        // sheetIndex.setPadding(new Insets(0,0,0,10));
        sheetIndex.setMaxWidth(50);

        sheetGroup.add(sheetindexL, 0, 0);
        sheetGroup.add(sheetIndex, 1, 0);
        //sheetGroup.setPadding(new Insets(0,0,0,10));

        //点击选择数据文件
        selectDataFile = new Button("选择文件");
        //点击选择目录
        selecttargetDir = new Button("选择目录");
        selectImgDir = new Button("选择目录");

        //生成
        createFile = new Button("生成文件");

        //清空
        clear = new Button("清空设置");

        GridPane gr = new GridPane();
        gr.setStyle("-fx-background-color: #efead0");
        gr.add(wenjian, 0, 0);
        gr.add(dataFile, 1, 0);

        gr.add(img, 0, 1);
        gr.add(imgDir, 1, 1);
        gr.add(selectImgDir, 2, 1);
        gr.add(imgDefault, 3, 1);

//        gr.add(sheetindexL, 3, 0);
//        gr.add(sheetIndex, 4, 0);
        gr.add(sheetGroup, 3, 0);

        gr.add(daochu, 0, 2);
        gr.add(targetDir, 1, 2);
        gr.add(selectDataFile, 2, 0);
        gr.add(selecttargetDir, 2, 2);


        //年龄限制
        wxnlLabel = new Label("微信导入年龄");
        wxnlLabel.setFont(new Font(20));

        wxnlJQDLabel = new Label("精确到:");
        wxnlJQDLabel.setPadding(new Insets(0, 0, 0, 10));
        wxnlJQDLabel.setFont(new Font(20));

        //微信年龄
        wxnlTextField = new TextField();
        wxnlTextField.setMaxWidth(50);


        //精确的年
        ToggleGroup nlGroup = new ToggleGroup();

        wxnln = new RadioButton("年");
        wxnln.setId("wxjqdn");
        wxnln.setPadding(new Insets(0, 10, 0, 10));
        wxnln.setOnMouseClicked(event -> {
            Utils.wxnljqd = "nian";
        });
        wxnln.setToggleGroup(nlGroup);


        wxnly = new RadioButton("月");
        wxnly.setId("wxjqdy");
        wxnly.setPadding(new Insets(0, 10, 0, 0));
        wxnly.setOnMouseClicked(event -> {
            Utils.wxnljqd = "yue";
        });
        wxnly.setToggleGroup(nlGroup);

        wxnlr = new RadioButton("日");
        wxnlr.setId("wxjqdr");
        wxnlr.setPadding(new Insets(0, 10, 0, 0));
        wxnlr.setOnMouseClicked(event -> {
            Utils.wxnljqd = "ri";
        });
        wxnlr.setToggleGroup(nlGroup);
        wxnlr.setSelected(true);

        GridPane gr2 = new GridPane();
        gr2.add(wxnlLabel, 0, 0);
        gr2.add(wxnlTextField, 1, 0);
        gr2.add(wxnlJQDLabel, 2, 0);
        gr2.add(wxnln, 3, 0);
        gr2.add(wxnly, 4, 0);
        gr2.add(wxnlr, 5, 0);


        gr.add(gr2, 1, 3);
        gr.add(createFile, 3, 5);
        gr.add(clear, 1, 5);


        gr.setAlignment(Pos.CENTER);
        gr.setHgap(10);//设置水平间距
        gr.setVgap(17);//设置垂直间距
        //  GridPane.setMargin(createFile, new Insets(0, 0, 0, 50));


        String sheetIndexValue = properties.getProperty("sheetIndex", "1");
        String dataFileValue = properties.getProperty("dataFile", "");
        String targetDirValue = properties.getProperty("targetDir", "");
        String imgDirValue = properties.getProperty("imgDir", "");
        String wxnlTextFieldValue = properties.getProperty("wxnlTextField", "12");
        String wxnljqdValue = properties.getProperty("wxnljqd", "ri");
        Utils.wxnljqd = wxnljqdValue;//设置年龄精确度
        dataFile.setText(dataFileValue);
        targetDir.setText(targetDirValue);
        imgDir.setText(imgDirValue);
        wxnlTextField.setText(wxnlTextFieldValue);
        sheetIndex.setText(sheetIndexValue);//设置数据的索引

        switch (wxnljqdValue) {
            case "nian":
                wxnln.setSelected(true);
                break;

            case "yue":
                wxnly.setSelected(true);
                break;
            case "ri":
                wxnlr.setSelected(true);
                break;
        }

        //清除事件
        clear.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                properties.clear();
                writeProperties();
                //选择文件
                String sheetIndexValue = properties.getProperty("sheetIndex", "1");
                String dataFileValue = properties.getProperty("dataFile", "");
                String targetDirValue = properties.getProperty("targetDir", "");
                String imgDirValue = properties.getProperty("imgDir", "");
                String wxnlTextFieldValue = properties.getProperty("wxnlTextField", "12");

                dataFile.setText(dataFileValue);
                targetDir.setText(targetDirValue);
                imgDir.setText(imgDirValue);
                wxnlTextField.setText(wxnlTextFieldValue);
                sheetIndex.setText(sheetIndexValue);//设置数据的索引

            }
        });
        selectDataFile.setOnAction(event -> {
            FileChooser fileChooser = new FileChooser();
            File selectedFile = fileChooser.showOpenDialog(primaryStage);
            if (selectedFile != null) {
                dataFile.setText(selectedFile.getAbsolutePath());
            }
        });
        //选择目标目录
        selecttargetDir.setOnAction(event -> {
            DirectoryChooser directoryChooser = new DirectoryChooser();
            File file = directoryChooser.showDialog(primaryStage);
            if (file != null) {
                targetDir.setText(file.getAbsolutePath());
            }

        });
        selectImgDir. setOnAction(event -> {
            DirectoryChooser directoryChooser = new DirectoryChooser();
            File file = directoryChooser.showDialog(primaryStage);
            if (file != null) {
                imgDir.setText(file.getAbsolutePath());
            }

        });

        createFile.setOnAction(event -> {
            try {
                writeProperties();
                //获取数据文件地址
                String dataFilePath = dataFile.getText();
             //   dataFilePath = dataFilePath == null ? dataFilePath : dataFilePath.replace("/", "\\");
                if (dataFilePath == null || "".equalsIgnoreCase(dataFilePath.trim()) || (!dataFilePath.contains(File.separator)&&!dataFilePath.contains("/")&&!dataFilePath.contains("\\"))) {
                    display("提示", "没有选择excel文件");
                    return;
                }
                //获取目标位置
                String targetDirPath = targetDir.getText();
             //   targetDirPath = targetDirPath == null ? targetDirPath : targetDirPath.replace("/", "\\");
                if (targetDirPath == null || "".equalsIgnoreCase(targetDirPath.trim()) || (!targetDirPath.contains(File.separator)&&!targetDirPath.contains("/")&&!targetDirPath.contains("\\"))) {
                    display("提示", "没有选择保存位置");
                    return;
                }


                int index = 2;//数据sheet的index位置,为了方便操作人员理解,从1开始,内部会减去1

                try {
                    index = Integer.parseInt(sheetIndex.getText());
                    if (index < 1) {
                        display("错误", "sheet的位置应该大于0");
                    }
                } catch (Exception e) {
                    // e.printStackTrace();
                    display("错误", "sheet的位置应该为数字");
                }
                String imgDirText = imgDir.getText();
                if (imgDirText == null || "".equals(imgDirText.trim())) {
                    imgDirText = dataFilePath;//默认的位置
                }

                if (imgDirText == null || "".equalsIgnoreCase(imgDirText.trim()) ||  (!imgDirText.contains(File.separator)&&!imgDirText.contains("/")&&!imgDirText.contains("\\"))) {
                    display("错误", "照片目录不正确");
                }

                // InputStream inputStream = MainApplication.class.getClassLoader().getResourceAsStream("a.xlsx");
                //  URL resource = MainApplication.class.getClassLoader().getResource(".");
//                display("", resource+"");
//                String path = resource.getPath();
//                if (path.startsWith("/")) {
//                    path = path.replaceFirst("/", "");
//                    System.err.println(path);
//                }
                    String wxnlTextFieldContent = wxnlTextField.getText();
                    try {
                        Utils.age = Integer.parseInt(wxnlTextFieldContent);
                    }catch (Exception e){
                        //e.printStackTrace();
                        wxnlTextFieldContent = "12";
                        Utils.age = 12;
                    }

                ExcelListener.isFirstHead = true;//刚开始执行
                Utils.crateExcel("a.xlsx", dataFilePath, imgDirText, index, targetDirPath, this);
            } catch (Exception e) {
                //  e.printStackTrace();
                if (e.getCause() != null && e.getCause().toString().contains("另一个程序正在使用此文件")) {
                    display("结果", "之前生成的excel文件正在被打开,关闭后重试");
                    return;
                }
                display("结果", "excel文件或者导出目录不存在");
                //display("debug",e.toString());
            }
        });

        Scene scene = new Scene(gr);
        primaryStage.setScene(scene);
        primaryStage.setTitle("数据表格生成");
        primaryStage.setWidth(960);
        primaryStage.setHeight(540);
        primaryStage.setResizable(true); //登录窗口的大小不允许改变
        primaryStage.show();

    }

    /**
     * 弹出窗口
     *
     * @param title
     * @param message
     */
    public void display(String title, String message) {
        Stage window = new Stage();
        window.setTitle(title);
        //modality要使用Modality.APPLICATION_MODEL
        window.initModality(Modality.APPLICATION_MODAL);
        window.setMinWidth(300);
        window.setMinHeight(150);

        Button button = new Button("关闭");
        button.setOnAction(e -> window.close());

        Label label = new Label(message);

        VBox layout = new VBox(10);
        layout.getChildren().addAll(label, button);
        layout.setAlignment(Pos.CENTER);

        Scene scene = new Scene(layout);
        window.setScene(scene);
        //使用showAndWait()先处理这个窗口，而如果不处理，main中的那个窗口不能响应
        window.showAndWait();
        window.setOnCloseRequest(event -> {
           System.exit(0);
        });
    }

    @Override
    public void onSuccess() {
        display("结果", "导出完成");
    }

    @Override
    public void onFail(String msg) {
        display("结果", msg);
    }


    private void writeProperties() {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {

                try {

                    //先获取数据
                    String dataFileContent = dataFile.getText();
                    dataFileContent = dataFileContent == null ? dataFileContent : dataFileContent.replace("\\", "/");
                    String imgDirContent = imgDir.getText();
                    imgDirContent = imgDirContent == null ? imgDirContent : imgDirContent.replace("\\", "/");
                    String targetDirContent = targetDir.getText();
                    targetDirContent = targetDirContent == null ? targetDirContent : targetDirContent.replace("\\", "/");
                    String sheetIndexContent = sheetIndex.getText();
                    String wxnlTextFieldContent = wxnlTextField.getText();

                    String jqd = null;
                    if (wxnln.isSelected()) {
                        jqd = "nian";
                    } else if (wxnly.isSelected()) {
                        jqd = "yue";
                    } else {
                        jqd = "ri";
                    }
                    StringBuffer stringBuffer = new StringBuffer();
                    put2Pro("sheetIndex", sheetIndexContent, stringBuffer);
                    put2Pro("dataFile", dataFileContent, stringBuffer);
                    put2Pro("targetDir", targetDirContent, stringBuffer);
                    put2Pro("imgDir", imgDirContent, stringBuffer);
                    put2Pro("wxnlTextField", wxnlTextFieldContent, stringBuffer);
                    put2Pro("wxnljqd", jqd, stringBuffer);

                    //display("config", path);
                    String configPath = path + "config.properties";
                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(configPath)));
                    bufferedWriter.write(stringBuffer.toString());
                    bufferedWriter.close();

                } catch (Exception e) {
                  //  e.printStackTrace();
                  //  display("info", e.toString());

                }
            }
        });

    }

//    private void put2Pro(String key, String value, Properties properties) {
//        if (key==null||"".equals(key.trim())||value==null||"".eq)
//    }

    private void put2Pro(String key, String value, StringBuffer stringBuffer) {
        if (key == null || "".equals(key.trim()) || value == null || "".equals(value.trim())) {
            return;
        }
//        if (!value.contains(File.separator+File.separator)) {
//            value.replace(File.separator, File.separator+File.separator);
//        }

        stringBuffer.append(key).append("=").append(value).append("\n");
    }


}
